#include <iostream> //对应 C里的 stdio.h
#include <string>   //C ++ string 类头文件
#include <cstring>  //string.h  C 字符串相关函数头文件
using namespace std;

class MyString {
    char* m_data;
    size_t m_length;

    void Copy(const char* str) {
        m_length = strlen(str);
        m_data = new char[m_length + 1];
        strcpy(m_data, str);
    }

public:
    //无参构造函数
    MyString() : m_data(NULL), m_length(0) {}

    //有参构造函数
    MyString(const char* str) {
        if (!str) {
            m_data = NULL;
            m_length = 0;
        } else {
            Copy(str);
        }
    }

    //拷贝构造函数
    MyString(const MyString& other) {
        Copy(other.m_data);
    }

    //析构函数
    ~MyString() {
        if (m_data) {
            delete[] m_data;
        }
    }

    //赋值运算符
    MyString& operator=(const MyString& other) {
        if (this != &other) {
            if (m_data) delete[] m_data;
            Copy(other.m_data);
        }
        return *this;
    }

    //字符串连接
    MyString operator+(const MyString& other) const {
        MyString result;
        result.m_length = m_length + other.m_length;
        result.m_data = new char[result.m_length + 1];
        strcpy(result.m_data, m_data);
        strcat(result.m_data, other.m_data);
        return result;
    }

    //输出运算符
    friend ostream& operator<<(ostream& os, const MyString& str) {
        if (str.m_data) os << str.m_data;
        return os;
    }

    //输入运算符
    friend istream& operator>>(istream& is, MyString& str) {
        char buffer[1024];
        is >> buffer;
        
        if (str.m_data) delete[] str.m_data;
        str.m_length = strlen(buffer);
        str.m_data = new char[str.m_length + 1];
        strcpy(str.m_data, buffer);
        
        return is;
    }

    size_t length() const { return m_length; }
    const char* c_str() const { return m_data; }
};


int main()
{
    // 无参构造
    MyString s1;
    cout << "s1: (默认值): " << s1 << " 长度: " << s1.length() << endl;

    // 有参构造
    MyString s2("Hello");
    cout << "s2: " << s2 << " 长度: " << s2.length() << endl;

    // 拷贝构造
    MyString s3 = s2;
    cout << "s3: (s2的拷贝): " << s3 << endl;

    // 字符串连接
    MyString s4 = s2 + " World";
    cout << "s4: (s2 + \"World\"): " << s4 << endl;

    // 输入输出
    MyString s5;
    cout << "s5: 输入一个字符串: ";
    cin >> s5;
    cout << "你输入的是: " << s5 << endl;

    return 0;
}